﻿using System;
using System.Data.SqlClient;
using DataCenter.Interface;
using DataCenter.Share;
using System.Diagnostics;

namespace DataCenter.App
{
    class Program
    {
        public const int SUCCESS = 1;
        public const int FAILED = 0;

        static int Main(string[] args)
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();

            Logger.GetInstance().Debug("[App Start]: " + DateTime.Now);

            AppDomain.CurrentDomain.UnhandledException +=
                new UnhandledExceptionEventHandler(UnhandledException);

            string dbName = "DataCenter";
            string objectIds = "";
            ExecTypes execType = ExecTypes.Import;
            DateTime time0 = Utils.EMPTY_TIME;
            DateTime time1 = Utils.EMPTY_TIME;

            if (!ParseArgs(args, ref dbName, ref execType, ref objectIds, ref time0, ref time1))
                return FAILED;

            Logger.GetInstance().DebugFormat("\tArgs: DB={0};ObjectIds={1};Oper={2};Time0={3};Time1={4}",
                new object[] { dbName, objectIds, execType, time0, time1 });

            SqlConnectionStringBuilder cnStrBuilder = new SqlConnectionStringBuilder();
            cnStrBuilder.DataSource = "localhost";
            cnStrBuilder.InitialCatalog = dbName;
            //cnStrBuilder.UserID = "sa";
            //cnStrBuilder.Password = "pass";
            cnStrBuilder.IntegratedSecurity = true;
            cnStrBuilder.Pooling = false;

            using (SqlConnection connection = new SqlConnection(cnStrBuilder.ConnectionString))
            {
                connection.Open();
                using (SqlCommand command = connection.CreateCommand())
                {
                    command.CommandTimeout = 0;

                    using (AppEntry entry = new AppEntry(command))
                    {
                        if (!entry.Initialize(objectIds, execType, time0, time1))
                            return FAILED;
                        if (!entry.Execute()) return FAILED;
                    }
                }
            }

            watch.Stop();
            Logger.GetInstance().Debug("[总时间]：" + watch.ElapsedMilliseconds);
            Logger.GetInstance().Debug("[App Stop]: " + DateTime.Now);

            return SUCCESS;
        }

        static bool ParseArgs(string[] args, ref string dbName, ref ExecTypes execType, ref string objectIds, ref DateTime time0, ref DateTime time1)
        {
            if (args.Length % 2 != 0)
                return Logger.GetInstance().Error("参数个数不匹配");

            for (int i = 0; i < args.Length; i += 2)
            {
                switch (args[i].ToUpper())
                {
                    case "DB":
                        if (string.IsNullOrEmpty(args[i + 1]))
                            return Logger.GetInstance().Error("参数DB不正确");
                        dbName = args[i + 1];
                        break;
                    case "ID": 
                        objectIds = Utils.ArrayToString(Algorithm.ParseTupleString(args[i + 1]));
                        break;
                    case "OPER":
                        if (string.IsNullOrEmpty(args[i + 1]))
                            return Logger.GetInstance().Error("参数TYPE不正确");
                        int iType;
                        if (!int.TryParse(args[i + 1], out iType))
                            return Logger.GetInstance().Error("参数TYPE不正确");
                        execType = (ExecTypes)iType;
                        break;
                    case "TIME0":
                        if (string.IsNullOrEmpty(args[i + 1]))
                            return Logger.GetInstance().Error("参数TIME0不正确");
                        if (!DateTime.TryParse(args[i + 1], out time0))
                            return Logger.GetInstance().Error("参数TIME0不正确");
                        break;
                    case "TIME1":
                        if (string.IsNullOrEmpty(args[i + 1]))
                            return Logger.GetInstance().Error("参数TIME1不正确");
                        if (!DateTime.TryParse(args[i + 1], out time1))
                            return Logger.GetInstance().Error("参数TIME1不正确");
                        break;
                }
            }

            return true;
        }

        static void UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = (Exception)e.ExceptionObject;
            Logger.GetInstance().Error("UnhandledException", ex);
        }
    }
}
